package com.weigecoder.warehouse.controller;

import com.weigecoder.warehouse.constant.WarehouseConstants;
import com.weigecoder.warehouse.dto.AssignAuthToUserDto;
import com.weigecoder.warehouse.dto.AssignRoleDto;
import com.weigecoder.warehouse.entity.Result;
import com.weigecoder.warehouse.entity.Role;
import com.weigecoder.warehouse.entity.User;
import com.weigecoder.warehouse.exception.BusinessException;
import com.weigecoder.warehouse.page.Page;
import com.weigecoder.warehouse.service.AuthService;
import com.weigecoder.warehouse.service.RoleService;
import com.weigecoder.warehouse.service.UserService;
import com.weigecoder.warehouse.utils.CurrentUser;
import com.weigecoder.warehouse.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

// @Api(tags = "用户管理")
@RequestMapping("/user")
@RestController
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private TokenUtils tokenUtils;
    @Autowired
    private AuthService authService;

    /**
     * 分页查询用户的url接口/user/user-list
     *
     * 参数Page对象用于接收请求参数页码pageNum、每页行数pageSize;
     * 参数User对象用于接收请求参数用户名userCode、用户类型userType、用户状态userState;
     *
     * 返回值Result对象向客户端响应组装了所有分页信息的Page对象;
     */
    // @ApiOperation(value = "分页查询用户")
    @GetMapping("/user-list")
    public Result userListPage(Page page, User user){
        //执行业务
        page = userService.queryUserPage(page, user);
        //响应
        return Result.ok(page);
    }

    /**
     * 添加用户的url接口/user/addUser
     *
     * @RequestBody User user将添加的用户信息的json串数据封装到参数User对象;
     * @RequestHeader(WarehouseConstants.HEADER_TOKEN_NAME) String token
     * 将请求头Token的值即客户端归还的token赋值给参数变量token;
     */
    @RequestMapping("/addUser")
    public Result addUser(@RequestBody User user,
                          @RequestHeader(WarehouseConstants.HEADER_TOKEN_NAME) String token){
        //获取当前登录的用户
        CurrentUser currentUser = tokenUtils.getCurrentUser(token);
        if (currentUser==null){
            throw new BusinessException("请登录！");
        }
        //获取当前登录的用户id,即创建新用户的用户id
        int createBy = currentUser.getUserId();
        user.setCreateBy(createBy);
        //执行业务
        return userService.saveUser(user);
    }

    /**
     * 修改用户状态的url接口/user/updateState
     *
     * @RequestBody User user将客户端传递的json数据封装到参数User对象中;
     * @RequestHeader(WarehouseConstants.HEADER_TOKEN_NAME) String token
     * 将请求头Token的值即客户端归还的token赋值给参数变量token;
     */
    @PutMapping("/updateState")
    public Result updateUserState(@RequestBody User user,
                                  @RequestHeader(WarehouseConstants.HEADER_TOKEN_NAME) String token){
        //获取当前登录的用户
        CurrentUser currentUser = tokenUtils.getCurrentUser(token);
        //获取当前登录的用户id,即修改用户的用户id
        int updateBy = currentUser.getUserId();

        //设置修改用户的用户id和修改时间
        user.setUpdateBy(updateBy);
        // user.setUpdateTime(new Date());   sql语句now()

        //执行业务
        Result result = userService.updateUserState(user);

        //响应
        return result;
    }

    /**
     * 查询用户已分配的角色的url接口/user/user-role-list/{userId}
     */
    @RequestMapping("/user-role-list/{userId}")
    public Result userRoleList(@PathVariable int userId){
        //执行业务
        List<Role> roleList = roleService.queryRolesByUserId(userId);
        //响应
        return Result.ok(roleList);
    }

    /**
     * 给用户分配角色的url接口/user/assignRole
     *
     * @RequestBody AssignRoleDto assignRoleDto将请求传递的json数据封装到参数AssignRoleDto对象中;
     */
    @PutMapping("/assignRole")
    public Result assignRole(@RequestBody AssignRoleDto assignRoleDto){
        //执行业务
        roleService.assignRole(assignRoleDto);
        //响应
        return Result.ok("分配角色成功！");
    }

    /**
     * 删除用户的url接口/user/deleteUser/{userId}
     */
    @DeleteMapping("/deleteUser/{userId}")
    public Result deleteUser(@PathVariable Integer userId){
        //执行业务
        Result result = userService.removeUserByIds(Arrays.asList(userId));
        //响应
        return result;
    }

    /**
     * 批量删除用户
     * @param userIds
     * @return
     */
    @DeleteMapping("/deleteUserList")
    public Result deleteUserBatch(@RequestBody List<Integer> userIds){
        //执行业务
        Result result = userService.removeUserByIds(userIds);
        //响应
        return result;
    }

    /**
     * 修改用户的url接口/user/updateUser
     *
     * @RequestBody User user将请求传递的json数据封装到参数User对象;
     * @RequestHeader(WarehouseConstants.HEADER_TOKEN_NAME) String token
     * 将请求头Token的值即客户端归还的token赋值给参数变量token;
     */
    @PutMapping("/updateUser")
    public Result updateUser(@RequestBody User user,
                             @RequestHeader(WarehouseConstants.HEADER_TOKEN_NAME) String token){
        //获取当前登录的用户
        CurrentUser currentUser = tokenUtils.getCurrentUser(token);
        //获取当前登录的用户id -- 修改用户的用户id
        user.setUpdateBy(currentUser.getUserId());

        //执行业务
        Result result = userService.updateUserName(user);

        //响应
        return result;
    }


    /**
     * 重置密码的url接口/user/updatePwd/{userId}
     */
    @RequestMapping("/updatePwd/{userId}")
    public Result resetPassWord(@PathVariable Integer userId){
        //执行业务
        Result result = userService.resetPwd(userId);
        //响应
        return result;
    }



    /**
     * // http://localhost:3000/api/user/user-auth?userId=33&_t=1692084360927
     *     // GET
     */
    @GetMapping("/user-auth")
    public Result GetUserAuthByUserId(Integer userId){
        //执行业务
        List<Integer> authIdList = roleService.queryAuthByUserId(userId);
        //响应
        return Result.ok(authIdList);
    }

    /**
     * 给用户分配权限
     * http://localhost:3000/api/user/auth-grant
     */
    @PutMapping("/auth-grant")
    public Result assignAuthToUser(@RequestBody AssignAuthToUserDto assignAuthToUserDto){
        //执行业务
        authService.assignAuthToUser(assignAuthToUserDto);
        return Result.ok("修改权限成功！");
    }
}
